﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using SeaBattle.Domain.Abstract.Services;
using SeaBattle.Domain.Entities;
using SeaBattle.Domain.Factory;
using SeaBattle.Web.Models.Lobby;

namespace SeaBattle.Web.Controllers
{
    [Authorize]
    public class LobbyController : Controller
    {
        private readonly IPlayerService _playerService;
        private readonly IGameService _gameService;

        public LobbyController()
        {
            _playerService = PlayerFactory.PlayerService;
            _gameService = GameFactory.GameService;
        }

        public ActionResult Index()
        {
            var player = _playerService.GetPlayer(User.Identity.Name);
            var balance = _playerService.GetPlayerBalance(player.Login);

            return View(new LobbyViewModel
                            {
                                PlayerAccountBalance = balance,
                            });
        }

        private IEnumerable<Game> GetGamesList()
        {
            var player = _playerService.GetPlayer(User.Identity.Name);
            return _gameService.GetGames().Where(x => x.State == GameState.StateOpened && x.Creator.Id != player.Id);
        }
        public ActionResult GamesList()
        {
            return View(GetGamesList());
        }

        public ActionResult GamesListUp()
        {
            var gameList = GetGamesList().OrderBy(x => x.Preset);
            return View("GamesList", gameList);
        }

        public ActionResult GamesListDown()
        {
            var gameList = GetGamesList().OrderByDescending(x => x.Preset);
            return View("GamesList", gameList);
        }

        public ActionResult CreateGame()
        {
            return PartialView(new CreateGameViewModel());
        }

        [HttpPost]
        public ActionResult CreateGame(CreateGameViewModel createGameViewModel)
        {
            var player = _playerService.GetPlayer(User.Identity.Name);
            var game = _gameService.CreateNewGame(createGameViewModel.Name, createGameViewModel.Preset, player);
            return View("Redirect", game.Id);
        }

        public ActionResult UserGamesList()
        {
            var player = _playerService.GetPlayer(User.Identity.Name);
            var gameList = _gameService.GetGames().Where(x => x.Creator.Id == player.Id).OrderBy(x => x.Created);
            var gameList2 = _gameService.GetGames().Where(x => x.Opponent != null && x.Opponent.Id == player.Id).OrderBy(x => x.Created);
            return View(gameList.Union(gameList2));
        }
    }
}
